package com.bugsnag.ohos;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

/**
 * Reads legacy information left in SharedPreferences and migrates it to the new location.
 *
 * @since 2021-07-01
 */
public class SharedPrefMigrator {
    private static final String INSTALL_ID_KEY = "install.iud";
    private static final String USER_ID_KEY = "user.id";
    private static final String USER_NAME_KEY = "user.name";
    private static final String USER_EMAIL_KEY = "user.email";

    Context context;
    Preferences prefs;

    /**
     * constructor
     *
     * @param context
     */
    public SharedPrefMigrator(Context context) {
        this.context = context;
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        prefs = databaseHelper.getPreferences("bugsnag_ohos");
    }

    /**
     * load device id
     *
     * @return device id
     */
    public String loadDeviceId() {
        return prefs.getString(INSTALL_ID_KEY, null);
    }

    /**
     * load user
     *
     * @param deviceId
     * @return user
     */
    public User loadUser(String deviceId) {
        return new User(
            prefs.getString(USER_ID_KEY, deviceId),
            prefs.getString(USER_EMAIL_KEY, null),
            prefs.getString(USER_NAME_KEY, null)
        );
    }

    /**
     * has prefs
     *
     * @return boolean
     */
    public boolean hasPrefs() {
        return loadDeviceId() != null;
    }

    /**
     * delete legacy prefs
     */
    public void deleteLegacyPrefs() {
        if (hasPrefs()) {
            prefs.clear();
        }
    }
}
